#-----------------------------------------------------------------------------
# Name:        BackUp.py
# Purpose:     
#
# Author:      Luigi Poderico
#
# Created:     2005/04/12
# RCS-ID:      $Id: BackUp.py $
# Copyright:   (c) 2002
# Licence:     <your licence>
#-----------------------------------------------------------------------------

import zipfile
import time

class BackUp:
   
    def __AddLocal(self, aDirInfo, aZipFile):
       """
       Add to aZipFile the files in aDirInfo tripe as returned by
       os.walk()
       """
       
       import os.path
       
       myPathBase = aDirInfo[0]
       
       for myFileName in aDirInfo[2]:
           myCompleteFileName = os.path.join(myPathBase, myFileName)
           print "Adding " + myCompleteFileName
           aZipFile.write(myCompleteFileName)
           pass
       
       pass 
   
#-------------------------------------------------------------------------------

    def __CheckDestination(self, aDestinationBackup):
        """
        """
        
        import os
        import os.path
        
        if os.path.isdir(aDestinationBackup):
            return
        
        os.mkdir(aDestinationBackup)
        
        pass
    
#-------------------------------------------------------------------------------
    
    def __TestZipBackup(self, aNameBackup):
        """
        Test the integrity of aNameBackup.
        """
        
        print "Testing backup integrity"
        time.sleep(3)
        
        myZipFile = zipfile.ZipFile(aNameBackup, 'r')
        myTest = myZipFile.testzip()
        
        if myTest != None:
            print "ERROR: Backup failed!"
            print myTest
            pass
        myZipFile.printdir()
        
        return
   
#-------------------------------------------------------------------------------
    
    def ZipBackup(self, aSourcesBackup, aDestinationBackup, aNameBackup):
        """
        Store recoursively the files in aSourceBackup in a zip file named
        aNameBackup.
        """
        import os
        import os.path
        
        self.__CheckDestination(aDestinationBackup)
        
        myNameBackup = os.path.join(aDestinationBackup, aNameBackup)
        
        myZipFile = zipfile.ZipFile(myNameBackup, 'w', zipfile.ZIP_DEFLATED)
        print "Performing backup", aNameBackup
        time.sleep(2)
        
        for mySourceBackup in aSourcesBackup:
            print mySourceBackup
            for myDirInfo in os.walk(mySourceBackup):
                self.__AddLocal(myDirInfo, myZipFile)
                pass
        
        myZipFile.close()
        
        self.__TestZipBackup(myNameBackup)
        pass
    
    pass ## class
